package fm.dongman.animefm.view.fragment

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v4.view.ViewPager
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import fm.dongman.animefm.R
import fm.dongman.animefm.contractlib.IModel
import fm.dongman.animefm.contractlib.contract.FArticleContract
import fm.dongman.animefm.view.activity.SingleActivity
import fm.dongman.animefm.view.activity.WebViewActivity
import fm.dongman.animefm.view.adapter.FArticlesLatestAdapter
import fm.dongman.animefm.view.transform.StackTransformer
import fm.dongman.animefm.view.util.ActivityHelper
import fm.dongman.animefm.view.util.BannerHelper
import fm.dongman.animefm.view.util.ToastHelper
import fm.dongman.animefm.view.widget.MultiStateLayout
import fm.dongman.modellib.StaticArea.Injection
import fm.dongman.modellib.model.ArticleModel
import fm.dongman.presenterlib.presenter.FArticlePresenter
import fm.dongman.presenterlib.util.NetworkHelper
import kotlinx.android.synthetic.main.fragment_find_article.*
import kotlinx.android.synthetic.main.layout_find_article.*
import org.jetbrains.anko.onClick

/**
 * 发现->漫圈页面
 * Created by shize on 2017/9/28.
 */
class FArticleFragment : BaseFragment(), FArticleContract.IFArticleView {
    private lateinit var mPresenter: FArticleContract.IFArticlePresenter // 全局数据控制器

    private val mFArticleHotList: ArrayList<IModel.IArticleModel> = ArrayList() // 热门文章
    private lateinit var mFArticleHotLatestAdapter: FArticlesLatestAdapter // 热门文章适配器

    private val mFArticleNewList: ArrayList<IModel.IArticleModel> = ArrayList() // 最新文章
    private lateinit var mFArticleNewLatestAdapter: FArticlesLatestAdapter // 最新文章适配器

    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View {
        val fragment = inflater?.inflate(R.layout.fragment_find_article, container, false)
        FArticlePresenter(this, Injection.provideFArticleRepository(container!!.context))
        return fragment!!
    }

    override fun initData() {
        loadingContent()
    }

    override fun bindData() {
        bindSwipe()
        bindClassify()
        bindAdapter()
        mPresenter.startLoad()
    }

    /**
     * 绑定刷新控件
     */
    private fun bindSwipe() {
        mSrlArticleLayout.setColorSchemeResources(R.color.primary)
        mSrlArticleLayout.setOnRefreshListener {
            mPresenter.refreshPage()
        }
    }

    /**
     * 绑定分类
     */
    private fun bindClassify() {
        mLlArticleCosplay.onClick {
            startArticleList(ArticleListFragment.TYPE_COSPLAY) // cosplay
        }
        mLlArticleComment.onClick {
            startArticleList(ArticleListFragment.TYPE_CARD) // 漫萜
        }
        mLlArticleInventory.onClick {
            startArticleList(ArticleListFragment.TYPE_INVENTORY) // 盘点
        }
        mLlArticleComic.onClick {
            startArticleList(ArticleListFragment.TYPE_COMIC) // 漫画
        }
        mLlArticleInfomation.onClick {
            startArticleList(ArticleListFragment.TYPE_INFO) // 情报
        }
        mTvFindArticleSearch.onClick {
            val intent = Intent(activity, SingleActivity::class.java)
            intent.putExtra(SingleActivity.EXTRA_NAME, SingleActivity.INTENT_EXTRA_SEARCH)
            ActivityHelper.startActivity(activity, intent)
        }
    }

    /**
     * 启动文章列表页
     * @param type 类型
     */
    private fun startArticleList(type:String){
        val intent = Intent(activity, SingleActivity::class.java)
        intent.putExtra(SingleActivity.EXTRA_NAME, SingleActivity.INTENT_EXTRA_ARTICLE_LIST)
        intent.putExtra(SingleActivity.BUNDLE_EXTRA_KEY_TYPE, type)
        ActivityHelper.startActivity(activity, intent)
    }

    /**
     * 绑定适配器
     */
    private fun bindAdapter() {
        // 热门文章
        mFArticleHotLatestAdapter = FArticlesLatestAdapter(mFArticleHotList, activity)
        mRvFindArticleHot.adapter = mFArticleHotLatestAdapter
        mRvFindArticleHot.layoutManager = LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false)
        // 最新文章
        mFArticleNewLatestAdapter = FArticlesLatestAdapter(mFArticleNewList, activity)
        mLvFindArticleNew.adapter = mFArticleNewLatestAdapter
        mLvFindArticleNew.layoutManager = LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false)
    }

    override fun setPresenter(presenter: FArticleContract.IFArticlePresenter) {
        mPresenter = presenter
    }

    override fun isActive(): Boolean = isAdded

    override fun getViewContext(): Context = activity

    override fun showNoNetwork() {
        mSrlArticleLayout?.isRefreshing = false
        mFArticleMultiStateLayout?.changeState(MultiStateLayout.NET_ERROR)
    }

    override fun showRefreshFailed() {
        mSrlArticleLayout?.isRefreshing = false
//        if (NetworkHelper.isNetworkAvailable(activity)) {
//            ToastHelper.getInstance(activity).showError("发现->漫圈页面加载失败！")
//            return
//        }
      //  Toast.makeText(activity, "没有连接网络！", Toast.LENGTH_LONG).show()
    }

    override fun showFArticleDynamic(dynamicArticles: List<IModel.IArticleModel>) {
        loadedContent()
        val imageList = ArrayList<String>()         //绑定轮播图
        dynamicArticles.forEach {
            imageList.add((it as ArticleModel).imgUrl)
            BannerHelper.getBannerImages(mFindSheetBanner, imageList)
            mTvFindSheetBannerTitle.text = (dynamicArticles[0] as ArticleModel).title
        }
        mFindSheetBanner.setOnItemClickListener { position ->
            // 横幅点击事件
            startActivity(WebViewActivity.getIntent(activity, (dynamicArticles[position] as ArticleModel).articleURL))
        }
        // 设置过渡器
        mFindSheetBanner.setPageTransformer(StackTransformer())
        bindBannerTitle(dynamicArticles)
    }

    /**
     * 绑定轮播图标题
     */
    private fun bindBannerTitle(list: List<IModel.IArticleModel>) {
        if (list.isEmpty()) return
        mTvFindSheetBannerTitle.text = (list[0] as ArticleModel).title
        mFindSheetBanner.onPageChangeListener = object : ViewPager.OnPageChangeListener {
            override fun onPageScrollStateChanged(state: Int) {}
            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {}
            override fun onPageSelected(position: Int) {
                mTvFindSheetBannerTitle.text = (list[position] as ArticleModel).title

            }
        }
    }

    override fun showFArticleHot(hotArticles: List<IModel.IArticleModel>) {
        mFArticleHotList.clear()
        mFArticleHotList.addAll(hotArticles)
        mFArticleHotLatestAdapter.notifyDataSetChanged()
    }

    override fun showFArticleNew(newArticles: List<IModel.IArticleModel>) {
        mFArticleNewList.clear()
        mFArticleNewList.addAll(newArticles)
        mFArticleNewLatestAdapter.notifyDataSetChanged()
    }

    /**
     * 加载中
     */
    private fun loadingContent() = mFArticleMultiStateLayout?.changeState(MultiStateLayout.LOADING)

    /**
     * 加载完成
     */
    private fun loadedContent() {
        mSrlArticleLayout?.isRefreshing = false
        mFArticleMultiStateLayout?.changeState(MultiStateLayout.SUCCESS)
    }

    override fun onResume() {
        super.onResume()
        mFindSheetBanner.startTurning(4000)
    }

    override fun onPause() {
        super.onPause()
        mFindSheetBanner.stopTurning()
    }

    companion object {
        private var FRAGMENT_INSTANCE: FArticleFragment? = null

        /**
         * 获取实例
         */
        fun getInstance(): FArticleFragment {
            if (FRAGMENT_INSTANCE == null) {
                FRAGMENT_INSTANCE = FArticleFragment()
            }
            return FRAGMENT_INSTANCE!!
        }

        /**
         * 销毁实例
         */
        fun destroyInstance() {
            FRAGMENT_INSTANCE = null
        }
    }
}